package scheduler;

import util.UserData;
import util.CalendarInterface;
//import util.Meal;
import java.util.*;

public class Generator {
	public static void start() {
		final CustomScheduler scheduler = new CustomScheduler();
		Timer timer = new Timer();
		timer.schedule(new TimerTask(){
			public void run() {
				Calendar today = new GregorianCalendar();
				Calendar end = new GregorianCalendar();
				end.add(Calendar.DAY_OF_MONTH,2*7);
				generate(today,end);
			}
		},10000,10000);

	}
	public static void generate(Calendar d1, Calendar d2) {
		final CustomScheduler scheduler = new CustomScheduler();

		CalendarInterface.MealEvent meal[] = null;
		try {
			meal = CalendarInterface.getMealsBetween(d1.getTime(),d2.getTime());
		} catch(Exception e) {};
		Calendar c = (Calendar)d1.clone(), day = new GregorianCalendar();
		while(c.before(d2)) {
			boolean skip=false;
			if(UserData.shouldGenerate(c.get(Calendar.DAY_OF_WEEK))){
				for(int j=0; j<meal.length; j++) {
					day.setTime(meal[j].getDate());
					if(c.get(Calendar.DAY_OF_YEAR)==day.get(Calendar.DAY_OF_YEAR)
						&& c.get(Calendar.YEAR)==day.get(Calendar.YEAR)) {
						skip=true;
						break;
					}
				}
				if(!skip) {
					String str = scheduler.getNextMeal().getName();
					CalendarInterface.MealEvent ev = new CalendarInterface.MealEvent();
					ev.setDate(c.getTime());
					ev.setMealName(str);
					ev.setSource("GEN");
					CalendarInterface.addMealEvent(ev);
				}
			}
			c.add(Calendar.DAY_OF_MONTH,1);
		}
	}
}
